import { app, BrowserWindow, ipcMain } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import myWindow from './windows'
let { mainWindow, childWindow } = myWindow()
app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  ipcMain.on('ping', () => console.log('pong'))
  mainWindow()

  // 获取版本号
  ipcMain.handle('get-version', () => {
    return app.getVersion()
  })
  ipcMain.handle('new-open', (_, param) => {
    childWindow(param)
  })

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) mainWindow()
  })
})

// 监听store仓库变化，广播给其他窗口
ipcMain.on('update-storage', (event, key, name) => {
  for (const currentWin of BrowserWindow.getAllWindows()) {
    const webContentsId = currentWin.webContents.id
    if (webContentsId !== event.sender.id) {
      currentWin.webContents.send('update-storage', key, name)
    }
  }
})


app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
